import path from 'path'
import pbjs from 'protobufjs-cli/pbjs'
import pbts from 'protobufjs-cli/pbts'
import { UseOptions } from '../../interface/cmd'
import { openFile } from '../cmd'

export default async function useBaseGenerator(
  filePath: string,
  option: UseOptions
): Promise<string> {
  const pbjsPath = await generatePbjs(filePath, option)
  const pbtsPATH = await generatePbts(pbjsPath)
  return pbtsPATH
}

/**
 * 生成js的方法
 * @param filePath proto文件件
 * @returns 生成js的地址
 */
async function generatePbjs(filePath: string, option: UseOptions): Promise<string> {
  // 生成js的路径
  const fileName = path.basename(filePath).replace('.proto', '.js')
  const pbjsFilePath = path.join(__dirname, option.path + fileName)
  console.log(pbjsFilePath)
  return new Promise((resolve, reject) => {
    // json-module, static-module
    pbjs.main(
      ['-t', 'static-module', '-w', 'commonjs', '-o', path.resolve(pbjsFilePath), filePath],
      (err) => {
        if (err) {
          reject(err)
        }
        // 返回js文件路径
        resolve(pbjsFilePath)
      }
    )
  })
}

/**
 * 生成.d.ts文件
 * @param pbjsPath 转换后获得的js文件路径
 * @returns 返回生成.d.ts路径
 */
async function generatePbts(pbjsPath: string): Promise<string> {
  // .d.ts的生成路径
  const pbTsPath = pbjsPath.replace('.js', '.d.ts')
  return new Promise((resolve, reject) => {
    pbts.main(['-p', './', '-o', pbTsPath, pbjsPath], (err) => {
      if (err) {
        reject(err)
      }
      resolve(pbTsPath)
    })
  })
}
